package com.yangjunli.bishe.controller;


import com.yangjunli.bishe.core.ReturnT;
import com.yangjunli.bishe.entity.Goods;
import com.yangjunli.bishe.mapper.GoodsMapper;
import com.yangjunli.bishe.service.IGoodsService;
import com.yangjunli.bishe.service.impl.GoodsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器  食物表
 * </p>
 *
 * @author jobob
 * @since 2020-04-04
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    private static final String QUERY_ALL= "all";

    @Autowired
    IGoodsService goodsService;

    @Resource
    GoodsMapper goodsMapper;


    @GetMapping("/{title}")
    public ReturnT<List<Goods>> queryGoods(@PathVariable("title") String title) {

        if(QUERY_ALL.equals(title)){
            List<Goods> goods = goodsMapper.queryListAll();
            return new ReturnT<>(goods);
        }else {
            List<Goods> goods = goodsMapper.queryByTitle(title);
            return new ReturnT<>(goods);
        }
    }


    @GetMapping("/documentDetails/{id}")
    public ModelAndView documentDetails(@PathVariable("id") String id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("documentDetails");
        modelAndView.addObject("id",id);
        return modelAndView;
    }




    @GetMapping("/id/{id}")
    public ReturnT<Goods> queryGoodsId(@PathVariable("id") Integer id) {
        Goods goods = new Goods();
        try {
            goods = goodsMapper.selectById(id);
        }catch (Exception e){
            return new ReturnT<>(100,"保存失败");
        }
        return new ReturnT<Goods>(goods);
    }



    @PostMapping
    public ReturnT saveGoods(@RequestBody Goods goods) {
        try {
            goodsService.save(goods);
        }catch (Exception e){
            return new ReturnT<>(100,"保存失败");
        }
        return new ReturnT<>(200,"保存成功");
    }

    @PutMapping
    public ReturnT update(@RequestBody Goods goods) {
        try {
            goodsService.updateById(goods);
        }catch (Exception e){
            return new ReturnT<>(100,"保存失败");
        }
        return new ReturnT<>(200,"保存成功");
    }


    @DeleteMapping("/{id}")
    public ReturnT del(@PathVariable("id") Integer id) {
        try {
            goodsService.removeById(id);
        }catch (Exception e){
            return new ReturnT<>(100,"保存失败");
        }
        return new ReturnT<>(200,"保存成功");
    }



}
